import json
import codecs
from pathlib import Path
from typing import Set


class Database:
    def __init__(self, file_name='/database.json'):
        self.data = {}
        self.data['admins'] = []
        self.data['users'] = {}
        folder = str(Path(__file__).parent.absolute())
        buf_data = {}
        with open(folder+file_name, 'r') as f:
            buf_data = json.loads(f.read())
        if buf_data == {} or buf_data == None:
            self.save_to_file()
        else:
            self.data = buf_data

    def get_admins(self):
        return self.data['admins']

    def is_admin(self, admin_id):
        return str(admin_id) in self.data['admins']

    def add_admin(self, admin_id):
        self.data['admins'].append(admin_id)
        self.save_to_file()

    def add_balance(self, userid, balance):
        userid = str(userid)
        self.data['users'][userid]['balance'] += int(balance)
        self.save_to_file()

    def get_balance(self, userid):
        userid = str(userid)
        return self.data['users'][userid]['balance']

    def decrease_balance(self, userid, amount):
        userid = str(userid)
        self.data['users'][userid]['balance'] -= amount
        self.save_to_file()

    def set_balance(self, userid, balance):
        userid = str(userid)
        balance = float(balance)
        self.data['users'][userid]['balance'] = balance
        self.save_to_file()

    def reset_balance(self, userid):
        userid = str(userid)
        self.data['users'][userid]['balance'] = 0
        self.save_to_file()

    def save_to_file(self, file_name='/database.json'):
        folder = str(Path(__file__).parent.absolute())
        f = codecs.open(folder+file_name, 'w', 'utf-8')
        f.write(json.dumps(self.data))
        f.close()

    def try_create_user(self, username: str, userid: int, balance: float):
        userid = str(userid)
        if userid not in self.data['users'].keys():
            user = {
                "name": username,
                "id": userid,
                "balance": balance
            }
            self.data['users'][userid] = user
            self.save_to_file()
        else:
            pass
